<template>
  <div class="defect-container">
    <!-- 搜索条件区域 -->
    <div class="search-box">
      <div class="search-item">
        <span class="search-label">缺陷描述</span>
        <el-input
          v-model="searchQuery.defect_name"
          placeholder="请输入缺陷描述"
          clearable
          @clear="handleSearchClear('defect_name')"
        ></el-input>
      </div>
      
      <!-- 修改检测项类型下拉框 -->
      <div class="search-item">
        <span class="search-label">检测项类型</span>
        <el-select
          v-model="searchQuery.index_type"
          placeholder="请选择检测项类型"
          clearable
          :loading="typeLoading"
          v-if="itemTypes.length > 0"
        >
          <el-option
            v-for="item in itemTypes"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-skeleton v-else :rows="1" style="width: 200px" />
      </div>
      
      <div class="search-item">
        <span class="search-label">缺陷等级</span>
        <el-select
          v-model="searchQuery.defect_level"
          placeholder="请选择缺陷等级"
          clearable
          :loading="levelLoading"
        >
          <el-option
            v-for="item in defectLevelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
      
      <div class="search-buttons">
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button type="primary" @click="openDialog('add')">添加缺陷</el-button>
      <el-button 
        type="danger" 
        :disabled="selectedDefects.length === 0"
        @click="batchDelete"
      >
        批量删除({{ selectedDefects.length }})
      </el-button>
    </div>

    <!-- 弹窗组件 -->
    <common-defects-dialog
      :visible.sync="dialogVisible"
      :title="dialogTitle"
      :form-data="formData"
      :is-edit-mode="isEditMode"
      :defect-level-options="defectLevelOptions"
      :item-types="itemTypes"  
      @submit="handleSubmit"
      @submit-success="handleSubmitSuccess"
    />
 
    <!-- 表格区域 -->
    <div class="table-box">
      <el-table 
        ref="defectTable"
        :data="defectList" 
        border 
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column 
          type="selection" 
          width="55"
          :selectable="selectable"
        ></el-table-column>
        <el-table-column prop="defect_name" label="缺陷名称" min-width="150"></el-table-column>
        <!-- 修改检测项类型显示 -->
        <el-table-column prop="index_type" label="检测项类型" width="120">
          <template slot-scope="scope">
            {{ getIndexTypeName(scope.row.index_type) }}
          </template>
        </el-table-column>
        <el-table-column prop="defect_level" label="缺陷等级" width="120">
          <template slot-scope="scope">
            <el-tag :type="getLevelTagType(scope.row.defect_level)">
              {{ getDefectLevelName(scope.row.defect_level) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="process_method" label="处置方法" min-width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.process_method || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.remark || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">修改</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-box">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="size"
        :current-page="current"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script>
import CommonDefectsDialog from './CommonDefectsAddUpdate.vue'
import request from '@/utils/request'

// 检测项类型映射关系
const INDEX_TYPE_MAP = {
  1: '外观',
  2: '视觉',
  3: '尺寸',
  4: '物理性能检测',
  5: '化学成分检测'
};

export default {
  components: {
    CommonDefectsDialog
  },
  data() {
    return {
      isEditMode: false,
      searchQuery: {
        defect_name: '',
        index_type: '',
        defect_level: ''
      },
      defectList: [],
      selectedDefects: [],
      total: 0,
      current: 1,
      size: 10,
      itemTypes: [],
      defectLevelOptions: [
        { value: 'CR', label: '致命缺陷' },
        { value: 'MAJ', label: '严重缺陷' },
        { value: 'MIN', label: '轻微缺陷' }
      ],
      loading: false,
      typeLoading: false,
      levelLoading: false,
      dialogVisible: false,
      dialogTitle: '添加常见缺陷',
      formData: {
        defect_id: null,
        defect_name: '',
        index_type: '',
        defect_level: 'CR',
        process_method: '',
        remark: ''
      }
    }
  },
  computed: {
    isAllSelected() {
      return this.selectedDefects.length === this.defectList.length && this.defectList.length > 0
    },
    isIndeterminate() {
      return this.selectedDefects.length > 0 && !this.isAllSelected
    }
  },
  created() {
    this.initPage()
  },
  methods: {
    // 添加检测项类型名称映射方法
    getIndexTypeName(value) {
      return INDEX_TYPE_MAP[value] || value;
    },
    async handleSubmitSuccess() {
      this.fetchDefectList() // 刷新列表
      this.$refs.defectTable.clearSelection() // 清除选中状态（可选）
    },
    async initPage() {
      try {
        this.loading = true
        await Promise.all([
          this.fetchItemTypes(),
          this.fetchDefectList()
        ])
      } catch (error) {
        this.handleApiError(error, '数据加载失败')
      } finally {
        this.loading = false
      }
    },

    async fetchItemTypes() {
      try {
        this.typeLoading = true;
        console.log('正在请求检测项类型...');
        
        const response = await request({
          url: '/ldzl-qc/qc/defect/selectQcDefectType',
          method: 'post'
        });

        
        const responseData = response;


        
         // 转换检测项类型数据，添加中文名称
        this.itemTypes = Array.isArray(responseData)
          ? responseData.map(item => {
              const value = item.index_type ?? item.value ?? '';
              return {
                value: value,
                label: INDEX_TYPE_MAP[value] || value
              };
            })
          : [];
        console.log('转换后的检测项:', this.itemTypes);

      } catch (error) {
        console.error('检测项类型请求失败:', error);
        
        if (error.response) {
          console.error('响应数据:', error.response.data);
          console.error('状态码:', error.response.status);
        }
        
        this.handleApiError(error, '检测项类型加载失败');
      } finally {
        this.typeLoading = false;
      }
    },
    
    async fetchDefectList() {
      try {
        this.loading = true;
        const queryParams = {
          pageNum: this.current,
          pageSize: this.size,
          ...(this.searchQuery.defect_name && { defect_name: this.searchQuery.defect_name }),
          ...(this.searchQuery.index_type && { index_type: this.searchQuery.index_type }),
          ...(this.searchQuery.defect_level && { defect_level: this.searchQuery.defect_level })
        };

        console.log('请求参数:', queryParams);
        
        const response = await request({
          url: '/ldzl-qc/qc/defect/selectQcDefectList',
          method: 'post',
          data: queryParams
        });
        
        console.log('完整响应:', response);
        
        this.defectList = response?.records || response?.data?.records || [];
        this.total = response?.total || response?.data?.total || 0;
        this.size = response?.size || response?.data?.size || 10;
        this.current = response?.current || response?.data?.current || 1;
        this.selectedDefects = [];
        
      } catch (error) {
        console.error('请求失败详情:', {
          error: error.response?.data || error.message,
          status: error.response?.status
        });
        this.handleApiError(error, '缺陷列表加载失败');
      } finally {
        this.loading = false;
      }
    },
    
    handleSearchClear(field) {
      this.searchQuery[field] = ''
      this.handleSearch()
    },
    
    handleSearch() {
      this.current = 1
      this.fetchDefectList()
    },
    
    handleReset() {
      this.searchQuery = {
        defect_name: '',
        index_type: '',
        defect_level: ''
      }
      this.current = 1
      this.fetchDefectList()
    },
    
    handleSelectionChange(val) {
      this.selectedDefects = val
    },
    
    batchDelete() {
      if (this.selectedDefects.length === 0) {
        this.$message.warning('请至少选择一项');
        return;
      }
      
      this.$confirm(`确定删除选中的 ${this.selectedDefects.length} 条缺陷记录吗?`, '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          const ids = this.selectedDefects.map(item => item.defect_id);
          
          console.log('准备发送批量删除请求，参数:', ids);
          
          const response = await request({
            url: '/ldzl-qc/qc/defect/deleteQcDefect',
            method: 'post',
            data: ids
          });
          
          console.log('批量删除响应:', response);
          
          if (response === true || response.success) {
            this.$message.success('批量删除成功');
            this.selectedDefects = [];
            this.fetchDefectList();
          } else {
            throw new Error(response.message || '批量删除失败');
          }
        } catch (error) {
          console.error('批量删除错误详情:', error);
          if (error.response) {
            console.error('响应数据:', error.response.data);
            console.error('状态码:', error.response.status);
          }
          this.$message.error(error.message || '批量删除失败');
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    
    selectable(row, index) {
      return true
    },
    
    getDefectLevelName(value) {
      const item = this.defectLevelOptions.find(i => i.value === value)
      return item ? item.label : value
    },
    
    getLevelTagType(level) {
      const map = {
        'CR': 'danger',
        'MAJ': 'warning',
        'MIN': 'success'
      }
      return map[level] || ''
    },
    
    openDialog(mode = 'add', rowData = null) {
      this.dialogVisible = true
      this.isEditMode = mode === 'edit'
      this.dialogTitle = this.isEditMode ? '编辑常见缺陷' : '添加常见缺陷'
      
      this.formData = this.isEditMode ? {
        defect_id: rowData.defect_id,
        defect_name: rowData.defect_name,
        index_type: rowData.index_type,
        defect_level: rowData.defect_level,
        process_method: rowData.process_method || '',
        remark: rowData.remark || ''
      } : {
        defect_id: null,
        defect_name: '',
        index_type: '',
        defect_level: 'CR',
        process_method: '',
        remark: ''
      }
    },
    
    handleSubmit(formData, callback) {
      const apiUrl = this.isEditMode 
        ? '/ldzl-qc/qc/defect/updateQcDefect'
        : '/ldzl-qc/qc/defect/insertQcDefect';
      
      request({
        url: apiUrl,
        method: 'post',
        data: formData
      })
      .then(() => {
        this.$message.success(this.isEditMode ? '修改成功' : '添加成功');
        this.dialogVisible = false;
        this.fetchDefectList();
        
        if (typeof callback === 'function') {
          callback();
        }
      })
      .catch(error => {
        this.handleApiError(error);
        if (typeof callback === 'function') {
          callback();
        }
      });
    },
    
    handleEdit(row) {
      this.openDialog('edit', row)
    },
    
    async handleDelete(row) {
      try {
        await this.$confirm('确定删除该缺陷记录吗?', '提示', {
          type: 'warning'
        })
        
        await request({
          url: '/ldzl-qc/qc/defect/deleteQcDefect',
          method: 'post',
          data: [row.defect_id]
        });
        
        this.$message.success('删除成功')
        this.fetchDefectList()
      } catch (error) {
        if (error !== 'cancel') {
          this.handleApiError(error, '删除失败')
        }
      }
    },
    
    handleSizeChange(val) {
      this.size = val
      this.fetchDefectList()
    },
    
    handlePageChange(val) {
      this.current = val
      this.fetchDefectList()
    },
    
    handleApiError(error, defaultMsg = '操作失败') {
      console.error('API Error:', error)
      const msg = error.response?.data?.message || defaultMsg
      this.$message.error(msg)
    }
  }
}
</script>

<style scoped>
.defect-container {
  padding: 20px;
  background: #fff;
}

.search-box {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20px;
  align-items: center;
}

.search-item {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 10px;
}

.search-label {
  min-width: 80px;
  text-align: right;
  padding-right: 10px;
  font-size: 14px;
}

.search-buttons {
  margin-left: 15px;
  margin-bottom: 10px;
}

.action-buttons {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.table-box {
  margin-top: 20px;
}

.pagination-box {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>         